import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart' ;
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mfkb/config/Config.dart';
import 'package:path_provider/path_provider.dart';
import 'package:toast/toast.dart';
import 'package:webview_flutter/webview_flutter.dart';

class News extends StatefulWidget {
  int bar = 0 ;
  Color color = Colors.grey ;
  String url ;
  String md ;
  dynamic font ;
  String md5 ;
  News({Key key , @required this.bar , @required this.color , @required this.md , @required this.font , this.url , this.md5}):super(key : key) ;
  @override
  _NewsState createState() => _NewsState();
}

class _NewsState extends State<News> {
  // webview的控制器
  WebViewController _controller ;
  bool loading = true ;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: widget.bar == 1 ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark ,
      child: Scaffold(
        body: Stack(
          children: <Widget>[
            Container(
              width: ScreenUtil().setWidth(375),
              child: Column(
                children: <Widget>[
                  Container(
                    height: MediaQuery.of(context).padding.top ,
                    color:widget.color ,
                  ) ,
                  Container(
                    height: 45 ,
                    color: widget.color ,
                    child: Row(
                      children: <Widget>[
                        Container(
                          width: 17,
                          height: 17,
                          margin: EdgeInsets.only(left:ScreenUtil().setWidth(19)),
                          child: GestureDetector(
                            child: Container(
                              width: 17,
                              height: 17,
                              child: Image.asset("assets/images/back.png" , fit: BoxFit.fill,),
                            ),
                            onTap: (){
                              Navigator.of(context).pop() ;
                            },
                          ),
                        ) ,
                        Expanded(
                          child: Container(
                            child: Center(
                              child: Text("咨询详情" , style: TextStyle(
                                color: Color.fromARGB(255, 19 , 28 , 53) ,
                                fontSize: ScreenUtil().setSp(16) ,
                                fontWeight: FontWeight.bold 
                              ),),
                            ),
                          ),
                        ) ,
                        Container(
                          height: 17,
                          width: 36,
                        )
                      ],
                    ),
                  ) ,
                  Expanded(
                    child: WebView(
                      initialUrl: Uri.encodeFull(widget.url) ,
                      javascriptMode: JavascriptMode.unrestricted ,
                      // webView加载完成事件
                      onWebViewCreated:(WebViewController controller) async{
                        _controller = controller ;
                      } ,
                      // webView请求拦截
                      navigationDelegate: (NavigationRequest request){
                        return NavigationDecision.prevent ;
                      } ,
                      onPageFinished: (str) async{
                        // _controller.evaluateJavascript("document.getElementById('content').innerHTML = '<table><tr><td>123</td><td>456</td></tr><tr><td>123</td><td>456</td></tr></table>'") ;
                        try{
                          var dir = await getExternalStorageDirectory() ;
                          var path = dir.path ;
                          File file = new File(path+"/news/font/"+widget.font["md5"]+".css") ;
                          var css = "./font/"+widget.font["md5"]+".css" ;
                          if(!await file.exists()){
                            Directory d = Directory(path+"/news/font") ;
                            if(!await d.exists()){
                              await d.create() ;
                            }
                            // 下载文件
                            try{
                              await Dio().download(Config().getImgHost()+widget.font["url"], path+"/news/font/"+widget.font["md5"]+".css") ;
                            }catch(e){
                              file.delete() ;
                            }
                          }
                          await _controller.evaluateJavascript("dynamicLoadCss('$css')") ;
                          // 判断md文件是否已经存在了
                          File marked = File(path+"/news/md/"+widget.md5+".js") ;
                          var js = "./md/"+widget.md5+".js" ;
                          print(js) ;
                          bool mExit = await marked.exists() ;
                          if(!mExit){
                            Directory d = Directory(path+"/news/md") ;
                            if(!await d.exists()){
                              await d.create() ;
                            }
                            // 下载md文件
                            await Dio().download(Config().getImgHost()+widget.md , path+"/123") ;
                            var data = await File(path+"/123").readAsString() ;
                            data = '''parse(function(){/*
$data
*/})''' ;
                            await marked.writeAsString(data) ;
                            await _controller.evaluateJavascript("dynamicLoadJs('$js')") ;
                          }else{
                            await _controller.evaluateJavascript("dynamicLoadJs('$js')") ;
                          }
                        }catch(e){
                          Toast.show("样式加载失败", context) ;
                        }
                        setState(() {
                          loading = false ;
                        }) ;
                      },
                    ),
                  )
                ],
              ),
            ) ,
            Visibility(
              visible: loading ,
              child: Container(
                color:Color.fromARGB(255, 246, 245, 248) ,
                child: Center(
                  child: CircularProgressIndicator() ,
                ),
              ),
            )
          ],
        ) ,
      ),
    ) ;
  }
  
  @override
  void dispose() {
    super.dispose();
  }
}